"""
Case Type   : 共享存储-系统内部工具-dsscmd
Case Name   : dsscmd工具重命名文件名
Create At   : 2023/4/14
Owner       : opentestcase019
Description :
    1.重命名文件名，指定old_name和new_name参数为正常值
    2.重命名文件名，指定old_name参数为不符合规范的文件名
    3.重命名文件名，指定new_name参数为不符合规范的文件名
    4.重命名文件名，指定new_name参数为已经存在的文件名
    5.重命名文件名，指定-U UDS:socket_domain参数为正常值
    6.重命名文件名，指定错误的-U UDS:socket_domain参数
    7.重命名文件名，指定权限不足的socket_domain
    8.在备机执行重命名文件名
    9.在集群停止的情况下执行
    10.在dss关闭的情况下执行
Expect      :
    1.重命名成功
    2.合理报错
    3.合理报错
    4.重命名成功，原已存在的文件被覆盖
    5.重命名成功
    6.合理报错Failed to get uds connection.
    7.合理报错Failed to get uds connection.
    8.重命名成功
    9.合理报错
    10.合理报错
History     :
"""
import os
import time
import unittest
from yat.test import Node
from yat.test import macro
from testcase.utils.Logger import Logger
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant

Primary_SH = CommonSH('PrimaryDbUser')


@unittest.skipIf(1 == Primary_SH.get_node_num(), '单机环境不执行')
class ShareStorageTool(unittest.TestCase):
    def setUp(self):
        self.logger = Logger()
        self.logger.info(f"-----{os.path.basename(__file__)} start-----")
        self.primary_node = Node('PrimaryDbUser')
        self.standby_node = Node('Standby1DbUser')
        self.common = Common()
        self.constant = Constant()
        self.file_name_1 = "file_dsscmd_0025_1"
        self.file_name_2 = "file_dsscmd_0025_2"
        self.file_name_63chars = \
            "file_dsscmd_0025_file_dsscmd_0025_file_dsscmd_0025_file_63chars"
        self.file_name_64chars = \
            "file_dsscmd_0025_file_dsscmd_0025_file_dsscmd_0025_file_64chars1"
        self.file_name_numbers = "0025"
        self.file_name_letters = "filedsscmd"
        self.new_file_name_1 = "new_file_dsscmd_0025_1"
        self.new_file_name_2 = "new_file_dsscmd_0025_2"
        self.new_file_name_63chars = \
            "new_file_dsscmd_0025_new_file_dsscmd_0025_new_file_dsscmd_63cha"
        self.new_file_name_numbers = "002502"
        self.new_file_name_letters = "newfiledsscmd"
        self.new_file_name_64chars = \
            "new_file_dsscmd_0025_new_file_dsscmd_0025_new_file_dsscmd_63char"
        self.logger.info("-----获取卷组名-----")
        execute_cmd = f"source {macro.DB_ENV_PATH};dsscmd lsvg"
        self.logger.info(execute_cmd)
        execute_msg = self.common.get_sh_result(self.primary_node, execute_cmd)
        self.assertIn("Succeed to display lsvg info.", execute_msg,
                      "获取卷组名失败")
        self.vgname = execute_msg.splitlines()[1].split()[0].strip()
        self.logger.info(self.vgname)

        self.file_path_1 = os.path.join(self.vgname, self.file_name_1)
        self.file_path_2 = os.path.join(self.vgname, self.file_name_2)
        self.file_path_63chars = os.path.join(self.vgname,
                                              self.file_name_63chars)
        self.file_path_numbers = os.path.join(self.vgname,
                                              self.file_name_numbers)
        self.file_path_letters = os.path.join(self.vgname,
                                              self.file_name_letters)
        self.file_path_64chars = os.path.join(self.vgname,
                                              self.file_name_64chars)
        self.new_file_path_1 = os.path.join(self.vgname, self.new_file_name_1)
        self.new_file_path_2 = os.path.join(self.vgname, self.new_file_name_2)
        self.new_file_path_63chars = os.path.join(self.vgname,
                                                  self.new_file_name_63chars)
        self.new_file_path_numbers = os.path.join(self.vgname,
                                                  self.new_file_name_numbers)
        self.new_file_path_letters = os.path.join(self.vgname,
                                                  self.new_file_name_letters)
        self.new_file_path_64chars = os.path.join(self.vgname,
                                                  self.new_file_name_64chars)

    def test_sharestorage_tool(self):
        step1 = "-----step1:重命名文件名，指定old_name和new_name参数为正常值;" \
                "expect:重命名成功-----"
        self.logger.info(step1)
        cmd_list = [self.file_path_1, self.file_path_63chars,
                    self.file_path_numbers, self.file_path_letters]
        for cmd in cmd_list:
            execute_cmd = f"source {macro.DB_ENV_PATH};dsscmd touch -p +{cmd}"
            self.logger.info(execute_cmd)
            execute_msg = self.common.get_sh_result(self.primary_node,
                                                    execute_cmd)
            self.assertIn(f"Succeed to create file, name is +{cmd}.",
                          execute_msg, "执行失败" + step1)
        cmd_dict = {
            f'{self.file_path_1}': f'{self.new_file_path_1}',
            f'{self.file_path_63chars}': f'{self.new_file_path_63chars}',
            f'{self.file_path_numbers}': f'{self.new_file_path_numbers}',
            f'{self.file_path_letters}': f'{self.new_file_path_letters}'}
        for i in range(0, 4):
            execute_cmd = f"source {macro.DB_ENV_PATH};" \
                          f"dsscmd rename -o +{list(cmd_dict.keys())[i]} " \
                          f"-n +{list(cmd_dict.values())[i]}"
            self.logger.info(execute_cmd)
            execute_msg = self.common.get_sh_result(self.primary_node,
                                                    execute_cmd)
            self.assertIn(f"Succeed to rename file, old name is "
                          f"+{list(cmd_dict.keys())[i]}, "
                          f"new name is +{list(cmd_dict.values())[i]}.",
                          execute_msg, "执行失败" + step1)

        step2 = "-----step2:重命名文件名，指定old_name参数为不符合规范的文件名;" \
                "expect:合理报错-----"
        self.logger.info(step2)
        cmd_list = [f'+{self.new_file_path_1}@#', f'+{self.file_path_64chars}',
                    f'+{self.new_file_path_1}文件',
                    f'+{self.new_file_path_1}_not_exists',
                    self.new_file_path_1]
        for cmd in cmd_list:
            execute_cmd = f"source {macro.DB_ENV_PATH};" \
                          f"dsscmd rename -o {cmd} -n +{self.file_path_1}"
            self.logger.info(execute_cmd)
            execute_msg = self.common.get_sh_result(self.primary_node,
                                                    execute_cmd)
            if cmd == cmd_list[1]:
                self.assertIn("Path  decode error name length should less "
                              "than 64", execute_msg, "执行失败" + step2)
            elif cmd == cmd_list[3]:
                self.assertIn(f"+{self.new_file_path_1}_not_exists does "
                              f"not exist", execute_msg, "执行失败" + step2)
            elif cmd == cmd_list[-1]:
                self.assertIn("decode error , path should start with +",
                              execute_msg, "执行失败" + step2)
            else:
                self.assertIn("decode error , path should be "
                              "[0~9,a~z,A~Z,-,_,/,.]",
                              execute_msg, "执行失败" + step2)

        step3 = "-----step3:重命名文件名，指定new_name参数为不符合规范的文件名;" \
                "expect:合理报错-----"
        self.logger.info(step3)
        cmd_list = [f'+{self.file_path_1}@#', f'+{self.file_path_64chars}',
                    f'+{self.file_path_1}文件', self.file_path_1]
        for cmd in cmd_list:
            execute_cmd = f"source {macro.DB_ENV_PATH};" \
                    f"dsscmd rename -o +{self.new_file_path_letters} -n {cmd}"
            self.logger.info(execute_cmd)
            execute_msg = self.common.get_sh_result(self.primary_node,
                                                    execute_cmd)
            if cmd == cmd_list[1]:
                self.assertIn("Path  decode error name length should less "
                              "than 64", execute_msg, "执行失败" + step3)
            elif cmd == cmd_list[-1]:
                self.assertIn("decode error , path should start with +",
                              execute_msg, "执行失败" + step3)
            else:
                self.assertIn("decode error , path should be "
                              "[0~9,a~z,A~Z,-,_,/,.]",
                              execute_msg, "执行失败" + step3)

        step4 = "-----step4:重命名文件名，指定new_name参数为已经存在的文件名;" \
                "expect:重命名成功，原已存在的文件被覆盖-----"
        self.logger.info(step4)
        execute_cmd = f"source {macro.DB_ENV_PATH};" \
                      f"dsscmd rename -o +{self.new_file_path_letters} " \
                      f"-n +{self.new_file_path_numbers}"
        self.logger.info(execute_cmd)
        execute_msg = self.common.get_sh_result(self.primary_node, execute_cmd)
        self.assertIn(f"Succeed to rename file, "
                      f"old name is +{self.new_file_path_letters}, "
                      f"new name is +{self.new_file_path_numbers}.",
                      execute_msg, "执行失败" + step4)
        execute_cmd = f"source {macro.DB_ENV_PATH};" \
                      f"dsscmd ls -p +{self.vgname}"
        self.logger.info(execute_cmd)
        execute_msg = self.common.get_sh_result(self.primary_node, execute_cmd)
        self.assertEquals(1, execute_msg.count(self.new_file_name_numbers))
        self.assertNotIn(self.new_file_name_letters,
                         execute_msg, "执行失败" + step4)

        step5 = "-----step5:重命名文件名，指定-U UDS:socket_domain参数为正常值;" \
                "expect:重命名成功-----"
        self.logger.info(step5)
        execute_cmd = f"source {macro.DB_ENV_PATH};" \
                      f"dsscmd touch -p +{self.file_path_2};" \
                      f"dsscmd rename -o +{self.file_path_2} " \
                      f"-n +{self.new_file_path_2} -U {macro.UDS_PATH}"
        self.logger.info(execute_cmd)
        execute_msg = self.common.get_sh_result(self.primary_node, execute_cmd)
        self.assertIn(f"Succeed to create file, name is +{self.file_path_2}.",
                      execute_msg, "执行失败" + step5)
        self.assertIn(f"Succeed to rename file, "
                      f"old name is +{self.file_path_2}, "
                      f"new name is +{self.new_file_path_2}.",
                      execute_msg, "执行失败" + step5)
        execute_cmd = f"source {macro.DB_ENV_PATH};" \
                      f"dsscmd ls -p +{self.vgname}"
        self.logger.info(execute_cmd)
        execute_msg = self.common.get_sh_result(self.primary_node, execute_cmd)
        self.assertIn(self.new_file_name_2, execute_msg, "执行失败" + step5)

        step6 = "-----step6:重命名文件名，指定错误的-U UDS:socket_domain参数;" \
                "expect:合理报错Failed to get uds connection.-----"
        self.logger.info(step6)
        execute_cmd = f"source {macro.DB_ENV_PATH};" \
                      f"dsscmd rename -o +{self.new_file_path_2} " \
                      f"-n +{self.file_path_2} -U {macro.UDS_PATH}.cfg"
        self.logger.info(execute_cmd)
        execute_msg = self.common.get_sh_result(self.primary_node, execute_cmd)
        self.assertIn(self.constant.failed_to_get_uds_connection,
                      execute_msg, "执行失败" + step6)

        step7 = "-----step7:重命名文件名，指定权限不足的socket_domain;" \
                "expect:合理报错Failed to get uds connection.-----"
        self.logger.info(step7)
        execute_cmd = f"source {macro.DB_ENV_PATH};" \
                      f"chmod 000 {macro.UDS_PATH[4::]};" \
                      f"dsscmd rename -o +{self.new_file_path_2} " \
                      f"-n +{self.file_path_2} -U {macro.UDS_PATH};" \
                      f"chmod 600 {macro.UDS_PATH[4::]}"
        self.logger.info(execute_cmd)
        execute_msg = self.common.get_sh_result(self.primary_node, execute_cmd)
        self.assertIn(self.constant.failed_to_get_uds_connection,
                      execute_msg, "执行失败" + step7)

        step8 = "-----step8:在备机执行重命名文件名;expect:重命名成功-----"
        self.logger.info(step8)
        execute_cmd = f"source {macro.DB_ENV_PATH};" \
                      f"dsscmd rename -o +{self.new_file_path_2} " \
                      f"-n +{self.file_path_2} -U {macro.UDS_PATH};"
        self.logger.info(execute_cmd)
        execute_msg = self.common.get_sh_result(self.standby_node, execute_cmd)
        self.assertIn(f"Succeed to rename file, old name is "
                      f"+{self.new_file_path_2}, new name is "
                      f"+{self.file_path_2}.", execute_msg, "执行失败" + step8)

        step9 = "-----step9:在集群停止的情况下执行;expect:合理报错-----"
        self.logger.info(step9)
        stop_msg = Primary_SH.exec_cm_ctl(mode='stop')
        self.logger.info(stop_msg)
        self.assertIn(self.constant.cm_stop_success_msg,
                      stop_msg, '执行失败' + step9)
        execute_cmd = f"source {macro.DB_ENV_PATH};" \
                      f"dsscmd rename -o +{self.file_path_2} " \
                      f"-n +{self.new_file_path_2} -U {macro.UDS_PATH}"
        self.logger.info(execute_cmd)
        execute_msg = self.common.get_sh_result(self.standby_node, execute_cmd)
        self.assertIn(self.constant.failed_to_get_uds_connection,
                      execute_msg, "执行失败" + step9)
        start_msg = Primary_SH.exec_cm_ctl(mode='start')
        self.logger.info(start_msg)
        self.assertIn(self.constant.cm_start_success_msg,
                      start_msg, '启动集群失败')
        time.sleep(30)
        status = Primary_SH.exec_cm_ctl(mode='query', param='-Cv')
        self.logger.info(status)
        self.assertIn('cluster_state   : Normal', status, "执行失败" + step9)

        step10 = "-----step10:在dss关闭的情况下执行;expect:合理报错-----"
        self.logger.info(step10)
        execute_cmd = f"source {macro.DB_ENV_PATH};" \
                      f"dsscmd stopdss;sleep 2;" \
                      f"dsscmd rename -o +{self.file_path_2} " \
                      f"-n +{self.new_file_path_2} -U {macro.UDS_PATH}"
        self.logger.info(execute_cmd)
        execute_msg = self.common.get_sh_result(self.primary_node, execute_cmd)
        self.assertIn(self.constant.failed_to_get_uds_connection,
                      execute_msg, "执行失败" + step10)

    def tearDown(self):
        self.logger.info("-----环境清理-----")
        status = Primary_SH.exec_cm_ctl(mode='query', param='-Cv')
        self.logger.info(status)
        if "cluster_state   : Normal" not in status:
            start_msg = Primary_SH.exec_cm_ctl(mode='start')
            self.logger.info(start_msg)
        time.sleep(30)
        status = Primary_SH.exec_cm_ctl(mode='query', param='-Cv')
        self.logger.info(status)
        execute_cmd = f"source {macro.DB_ENV_PATH};" \
                      f"dsscmd rm -p +{self.new_file_path_1};" \
                      f"dsscmd rm -p +{self.file_path_2};" \
                      f"dsscmd rm -p +{self.new_file_path_numbers};" \
                      f"dsscmd rm -p +{self.new_file_path_63chars}"
        self.logger.info(execute_cmd)
        execute_msg = self.common.get_sh_result(self.primary_node, execute_cmd)
        self.assertIn('cluster_state   : Normal', status, '恢复环境失败')
        self.assertEquals(4, execute_msg.count("Succeed to remove device"),
                          "环境清理失败")
        self.logger.info(f"-----{os.path.basename(__file__)} end-----")
